package com.iqiyi.pps.epg.api.server.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.pps.epg.api.aop.annotation.SkipAuthCheck;
import com.iqiyi.pps.epg.api.aop.annotation.SkipInterfaceLog;
import com.iqiyi.pps.epg.api.aop.annotation.ValidateFiled;
import com.iqiyi.pps.epg.api.aop.annotation.ValidateGroup;
import com.iqiyi.pps.epg.api.model.web.carousel.*;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.server.web.carousel.CarouselWebService;
import com.iqiyi.pps.epg.api.utils.Constants;
import com.iqiyi.pps.epg.api.utils.DateTimeUtil;
import com.iqiyi.pps.epg.api.utils.RegUtil;
import com.iqiyi.pps.epg.api.utils.ServiceUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by karkarrotxu on 2016/9/19.
 */
@Service
public class CarouselProxy extends BaseProxy {
    private static Logger logger = LoggerFactory.getLogger(CarouselProxy.class);

    public String carouselCreate(String fatherId, String qipuId, String showName, String startTime, String itemTime,
                                 String startNum, String followNum, String totalNum, String repeatedStatus, String followedStatus,
                                 String channelTag, String copyrightEndTime, String bossStatus, String publishStatus,
                                 String createDays, String createStartTime, String pageUrl, String actualNum) {
        try {     // Check the parameters to make sure the format.
            if (!RegUtil.isPositiveInteger(fatherId) || !RegUtil.isPositiveInteger(qipuId) || StringUtils.isBlank(showName) ||
                    !RegUtil.isDateFormat(startTime) || StringUtils.isBlank(itemTime) || !RegUtil.isPositiveInteger(startNum)
                    || !RegUtil.isPositiveInteger(followNum) || !RegUtil.isPositiveInteger(totalNum) || !RegUtil.isPositiveInteger
                    (repeatedStatus) || !RegUtil.isPositiveInteger(followedStatus) || !RegUtil.isPositiveInteger(actualNum) || StringUtils.isBlank(copyrightEndTime)) {
                return ServiceUtil.getResponseError("参数不全，请补齐");
            }

            // Check the "channelTag" according to the "qipuId"
            // 播单没有channelTag, 且"qipuId"以“02”结尾的是播单的内容
            if (!qipuId.endsWith("02") && StringUtils.isBlank(channelTag)) {
                return ServiceUtil.getResponseError("参数不全，请补齐");
            }

            // Check the "followNum"
            if ("0".equals(followNum.trim()) || "0".equals(totalNum.trim())) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }

            if (Integer.parseInt(totalNum) < Integer.parseInt(followNum)) {
                return ServiceUtil.getResponseError("不能大于专辑、播单总集数");
            }

            TCarousel tCarousel = new TCarousel();
            tCarousel.setFatherId(Long.parseLong(fatherId));
            tCarousel.setQipuId(Long.parseLong(qipuId));
            tCarousel.setShowName(showName);
            tCarousel.setStartTime(startTime);
            tCarousel.setItemTime(Integer.parseInt(itemTime));
            tCarousel.setRepeatedStatus(Integer.parseInt(repeatedStatus));
            tCarousel.setFollowedStatus(Integer.parseInt(followedStatus));
            tCarousel.setTotalNum(Integer.parseInt(totalNum));
            tCarousel.setActualNum(Integer.parseInt(actualNum));
            tCarousel.setFollowNum(Integer.parseInt(followNum));
            tCarousel.setStartNum(Integer.parseInt(startNum));

            if (RegUtil.isDateFormat(startTime)) {
                // Date startTimeDate = DateTimeUtil.t
                long startTimeLong = DateTimeUtil.parseToLong(startTime);
                // Reserve enough time for data operation (default: 120 mins)
                long reserveMins = Configuration.getLong("carousel.create.reserve.time");

                // 提供 0 分钟前台操作缓冲时间
                long reserveTime = reserveMins * 60 * 1000;
                if (startTimeLong - System.currentTimeMillis() <= reserveTime) {
                    return ServiceUtil.getResponseError("只能创建" + reserveMins + "分钟后的节目");
                }

                // Calculate the 'EndTime' according to the 'StartTime' and 'ItemTime' and 'totalNum'.
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(startTimeLong);

                int checkNum = tCarousel.getTotalNum();
                int tempFollowNum = tCarousel.getFollowNum();
                if (tCarousel.getRepeatedStatus() != 1 && tCarousel.getFollowedStatus() != 1) {
                    //初次创建时 取小值
                    if (checkNum > tCarousel.getActualNum()) {
                        checkNum = tCarousel.getActualNum();
                    }
                    //  checkNum = tCarousel.getActualNum();
                    if (checkNum == 0) {
                        return ServiceUtil.getResponseError("没有实际数据，不能创建对应规则");
                    }
                }
                // The date need to be added to the startTime.
                int tempAddDay = checkNum / tempFollowNum - (checkNum % tempFollowNum == 0 ? 1 : 0);
                calendar.add(Calendar.DATE, tempAddDay);
                tCarousel.setEndTime(DateTimeUtil.transLongFormat(calendar.getTime().getTime()));
            } else {
                return ServiceUtil.getResponseError("时间格式错误");
            }

            tCarousel.setChannelTag(channelTag);

            tCarousel.setCopyrightEndTime(copyrightEndTime);
            tCarousel.setBossStatus(Integer.parseInt(StringUtils.isBlank(bossStatus) ? "1" : bossStatus));
            tCarousel.setPublishStatus(Integer.parseInt(StringUtils.isBlank(publishStatus) ? "2" : publishStatus));

            tCarousel.setOpUser(ServiceUtil.getOpUser());
            tCarousel.setPageUrl(pageUrl);
            if (!RegUtil.isDateFormat(createStartTime)) {
                createStartTime = startTime;
            }
            tCarousel.setCreateStartTime(createStartTime);
            tCarousel.setCreateDays(createDays);

            CarouselWebService.Iface service = getCarouselService();
            long result = service.create(tCarousel);

            writeChannelLog(Long.parseLong(fatherId), Constants.LogType.CAROUSEL_CREATE.getIndex(), ServiceUtil.getOpUser(),
                    (result > 0 ? Constants.CODE_SUC : Constants.CODE_FAIL) + "|" + getStrParam());

            if (result > 0) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "创建成功");
            } else {
                return ServiceUtil.getResponseError("创建失败");
            }
        } catch (Exception e) {
            logger.error("[carouselCreate]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    public String carouselDel(String ids, String fatherId) {
        try {
            if (StringUtils.isBlank(ids) || !RegUtil.isPositiveInteger(fatherId)) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            CarouselWebService.Iface service = getCarouselService();
            boolean result = service.delCarousel(ids);
            writeChannelLog(Long.parseLong(fatherId), Constants.LogType.CAROUSEL_DEL.getIndex(), ServiceUtil.getOpUser(), (result ? Constants.CODE_SUC : Constants.CODE_FAIL) + "|" + getStrParam());
            if (result) {
                return Constants.getJsonResponse(Constants.CODE_SUC, null, "操作成功");
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }

        } catch (Exception e) {
            logger.error("[carouselDel]", e);
            return ServiceUtil.getResponseError("删除删除自动规则异常");
        }
    }

    // 轮播台 - 获取自动规则列表
    @SkipInterfaceLog
    public String carouselGet(String fatherId, Integer pageNo, Integer pageSize) {
        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
        try {
            if (!RegUtil.isPositiveInteger(fatherId)) {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            Map<String, String> params = new HashMap();
            TFilter tFilter = new TFilter();
            params.put("EQL_fatherId", fatherId);
            params.put("NEQI_status", "-1");
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "repeatedStatus,endTime", "asc,desc", true);
            CarouselWebService.Iface service = getCarouselService();
            TCarouselPage result = service.carouselList(page, tFilter);

            writeChannelLog(Long.parseLong(fatherId), Constants.LogType.CAROUSEL_GET.getIndex(), ServiceUtil.getOpUser(),
                    (null != result ? Constants.CODE_SUC : Constants.CODE_FAIL) + "|" +
                            Constants.getResponse(Constants.CODE_SUC, result, null).toJsonString());

            if (null != result) {
                return Constants.getResponse(Constants.CODE_SUC, result, null).toJsonString();
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
        } catch (Exception e) {
            logger.error("[carouselGet]", e);
            return ServiceUtil.getResponseError(PARAMETER_ERROR);
        }
    }

    @SkipInterfaceLog
    public String getCarouselAutomationList(long channelId, Integer pageNo, Integer pageSize) {
        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
        try {
            Map<String, String> params = new HashMap<String, String>();
            TFilter tFilter = new TFilter();
            params.put("EQL_fatherId", channelId + "");
            params.put("GTI_status", "-1");
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "execIndex,lastSortTime", "asc,desc", true);
            TAutomationPage result = getCarouselService().automationList(page, tFilter);
            if (null != result) {
                return Constants.getResponse(Constants.CODE_SUC, result, null).toJsonString();
            } else {
                return ServiceUtil.getResponseError(PARAMETER_ERROR);
            }

        } catch (Exception e) {
            logger.error("[getCarouselAutomationList]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }

    }

    public String addCarouselAutomation(String data) {
        String jsonStrResp = "";
        try {
            TCarouselAutomation entity = JSONObject.parseObject(data, TCarouselAutomation.class);
            Map<String, String> params = new HashMap<String, String>();
            TFilter tFilter = new TFilter();
            params.put("EQL_fatherId", entity.getFatherId() + "");
            params.put("EQI_status", "1");
            tFilter.setFilters(params);
            TPage page = new TPage(-1, 1, 1, "execIndex,lastSortTime", "asc,desc", false);
            CarouselWebService.Iface service = getCarouselService();
            TAutomationPage resultPage = service.automationList(page, tFilter);
            if (resultPage.getResult().size() > 0) {
                return ServiceUtil.getResponseError(FORBIDDEN_ADD_RULE_ERROR);
            }

            entity.setOpUser(ServiceUtil.getOpUser());
            long result = service.createAutomation(entity);
            String code = null;
            if (result > 0) {
                code = Constants.CODE_SUC;
                jsonStrResp = Constants.getJsonResponse(Constants.CODE_SUC, null, Constants.getCode(code));
            } else if (result == -2) {
                code = Constants.CODE_ERROR_AUTOMATION_RUNNING;
                jsonStrResp = ServiceUtil.getResponseError(Constants.getCode(code));
            } else {
                code = Constants.CODE_ERROR;
                jsonStrResp = ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            writeChannelLog(entity.getFatherId(), Constants.LogType.CAROUSEL_AUTOMATION_CREATE.getIndex(), ServiceUtil.getOpUser(), Constants.getCode(code) + "|" + getStrParam());
            return jsonStrResp;
        } catch (Exception e) {
            logger.error("[addCarouselAutomation]", e);
            return ServiceUtil.getResponseError(ERROR_EXIST);
        }
    }

    public String changeStatusCarouselAutomation(long channelId, int execStatus) {
        String jsonStrResp = "";
        try {
            long result = getCarouselService().changeAutomationStatus(channelId, execStatus);
            String code = null;
            switch ((int) result) {
                case 1:
                    code = Constants.CODE_SUC;
                    jsonStrResp = Constants.getJsonResponse(Constants.CODE_SUC, null, Constants.getCode(code));
                    break;
                case -2:
                    code = Constants.CODE_ERROR;
                    jsonStrResp = ServiceUtil.getResponseError(EXECUTE_RULE_RUNNING_ERROR);
                    break;
                case -1:
                    code = Constants.CODE_ERROR;
                    jsonStrResp = ServiceUtil.getResponseError(NO_EXECUTE_RULE_ERROR);
                    break;
                case 0:
                    code = Constants.CODE_ERROR;
                    jsonStrResp = ServiceUtil.getResponseError(PARAMETER_ERROR);
                    break;
            }
            writeChannelLog(channelId, Constants.LogType.CAROUSEL_AUTOMATION_STATUS.getIndex(), ServiceUtil.getOpUser(), Constants.getCode(code) + "|" + getStrParam());
        } catch (Exception e) {
            logger.error("[changeStatusCarouselAutomation]", e);
            jsonStrResp = ServiceUtil.getResponseError(ERROR_EXIST);
        }
        return jsonStrResp;
    }

    /**
     * 轮播台自动化表单
     */
    public String delCarouselAutomation(String ids, long channelId) {
        String jsonStrResp = null;
        try {
            boolean result = getCarouselService().delAutomation(ids);
            String code = null;
            if (result) {
                code = Constants.CODE_SUC;
                jsonStrResp = Constants.getResponseList(Constants.CODE_SUC, null, Constants.getCode(code)).toJsonString();
            } else {
                code = Constants.CODE_ERROR;
                jsonStrResp = ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            writeChannelLog(channelId, Constants.LogType.CAROUSEL_AUTOMATION_DEL.getIndex(), ServiceUtil.getOpUser(), Constants.getCode(code) + "|" + getStrParam());
        } catch (Exception e) {
            logger.error("[delCarouselAutomation]", e);
            jsonStrResp = ServiceUtil.getResponseError(ERROR_EXIST);
        }
        return jsonStrResp;
    }

    public String moveAutomationIndex(long id, long aimId, long channelId) {
        String jsonStrResp = null;
        try {
            int result = getCarouselService().indexMoveAutomation(id, aimId);
            String code = null;
            if (result > 0) {
                code = Constants.CODE_SUC;
                jsonStrResp = Constants.getResponseList(Constants.CODE_SUC, null, Constants.getCode(code)).toJsonString();
            } else if (result == -2) {
                code = Constants.CODE_ERROR_AUTOMATION_RUNNING;
                jsonStrResp = Constants.getResponseList(Constants.CODE_ERROR, null, Constants.getCode(code)).toJsonString();
            } else {
                code = Constants.CODE_ERROR;
                jsonStrResp = ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            writeChannelLog(channelId, Constants.LogType.CAROUSEL_AUTOMATION_INDEX_MOVE.getIndex(), ServiceUtil.getOpUser(), Constants.getCode(code) + "|" + getStrParam());
        } catch (Exception e) {
            logger.error("[moveAutomationIndex]", e);
            jsonStrResp = ServiceUtil.getResponseError(ERROR_EXIST);
        }
        return jsonStrResp;
    }

    public String carouselEpisodeBatchDel(String ids, String channelId) {
        String jsonStrResp = null;
        try {
            if (!RegUtil.isPositiveInteger(channelId)) {
                jsonStrResp = ServiceUtil.getResponseFail("频道ID错误");
                return jsonStrResp;
            }
            List<Long> idList = JSONArray.parseArray(ids, Long.class);
            String result = getCarouselService().batchDelEpisode(idList, Long.valueOf(channelId));
            if (null == result) {
                jsonStrResp = ServiceUtil.getResponseError("批量删除失败");
            } else {
                JSONObject decode = JSON.parseObject(result);
                jsonStrResp = Constants.getJsonResponse(Constants.CODE_SUC.equals(decode.getString("ret")) ? Constants.CODE_SUC : Constants.CODE_ERROR, null, decode.getString("ret_msg"));
            }

            writeChannelLog(Long.valueOf(channelId), Constants.LogType.CAROUSEL_EPISODE_BATCH_DEL.getIndex(), null, result + "|" + getStrParam());
        } catch (Exception e) {
            logger.error("[carouselEpisodeBatchDel]", e);
            jsonStrResp = ServiceUtil.getResponseError(ERROR_EXIST);
        }
        return jsonStrResp;
    }

    public String carouselEpisodeBatchAdd(String dataString, String fatherId) {
        String jsonStrResp = null;
        try {
            if (!RegUtil.isPositiveInteger(fatherId)) {
                jsonStrResp = ServiceUtil.getResponseFail("频道ID错误");
                return jsonStrResp;
            }

            List<Long> idList = JSONArray.parseArray(dataString, Long.class);
            String result = getCarouselService().batchAddEpisode(idList, Long.valueOf(fatherId), ServiceUtil.getOpUser());
            if (null == result) {
                jsonStrResp = ServiceUtil.getResponseError("插入失败:" + result);
            } else {
                JSONObject decode = JSON.parseObject(result);
                jsonStrResp = Constants.getJsonResponse(Constants.CODE_SUC.equals(decode.getString("ret")) ? Constants.CODE_SUC : Constants.CODE_ERROR, null, result);
            }
            writeChannelLog(Long.valueOf(fatherId), Constants.LogType.CAROUSEL_EPISODE_BATCH_ADD.getIndex(), null, result + "|" + getStrParam());
        } catch (Exception e) {
            logger.error("[batchAdd]", e);
            jsonStrResp = ServiceUtil.getResponseError(ERROR_EXIST);
        }
        return jsonStrResp;
    }

    @SkipInterfaceLog
    public String getCarouselEpisodeList(long channelId, Integer pageNo, Integer pageSize) {
        String jsonStrResp = null;
        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
        try {
            Map<String, String> params = new HashMap<String, String>();
            TFilter tFilter = new TFilter();
            params.put("EQL_fatherId", channelId + "");
            params.put("GTI_status", "-1");
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "execIndex,lastSortTime", "asc,desc", true);
            TCarouselEpisodePage result = getCarouselService().carouselEpisodeList(page, tFilter);
            if (null != result) {
                jsonStrResp = Constants.getResponse(Constants.CODE_SUC, result, null).toJsonString();
            } else {
                jsonStrResp = ServiceUtil.getResponseError(PARAMETER_ERROR);
            }

        } catch (Exception e) {
            logger.error("[getCarouselEpisodeList]", e);
            jsonStrResp = ServiceUtil.getResponseError(ERROR_EXIST);
        }
        return jsonStrResp;
    }

    public String moveCarouselEpisodeIndex(long id, long aimId, long channelId) {
        String jsonStrResp = null;
        try {
            int result = getCarouselService().indexMoveEpisode(id, aimId);
            String code = null;
            if (result > 0) {
                code = Constants.CODE_SUC;
                jsonStrResp = Constants.getResponseList(Constants.CODE_SUC, null, Constants.getCode(code)).toJsonString();
            } else if (result == -2) {
                code = Constants.CODE_ERROR_AUTOMATION_RUNNING;
                jsonStrResp = Constants.getResponseList(Constants.CODE_ERROR, null, Constants.getCode(code)).toJsonString();
            } else {
                code = Constants.CODE_ERROR;
                jsonStrResp = ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            writeChannelLog(channelId, Constants.LogType.CAROUSEL_EPISODE_INDEX_MOVE.getIndex(), "", Constants.getCode(code) + "|" + getStrParam());
        } catch (Exception e) {
            logger.error("[moveCarouselEpisodeIndex]", e);
            jsonStrResp = ServiceUtil.getResponseError(ERROR_EXIST);
        }
        return jsonStrResp;
    }


    public String moveCarouselEpisodeIndexByIndex(long id, int aimIdx, long channelId) {
        String jsonStrResp = null;
        try {
            int result = getCarouselService().indexMoveEpisodeByIndex(id, aimIdx);
            String code = null;
            if (result > 0) {
                code = Constants.CODE_SUC;
                jsonStrResp = Constants.getResponseList(Constants.CODE_SUC, null, Constants.getCode(code)).toJsonString();
            } else if (result == -2) {
                code = Constants.CODE_ERROR_AUTOMATION_RUNNING;
                jsonStrResp = Constants.getResponseList(Constants.CODE_ERROR, null, Constants.getCode(code)).toJsonString();
            } else {
                code = Constants.CODE_ERROR;
                jsonStrResp = ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            writeChannelLog(channelId, Constants.LogType.CAROUSEL_EPISODE_INDEX_MOVE.getIndex(), "", Constants.getCode(code) + "|" + getStrParam());
        } catch (Exception e) {
            logger.error("[moveCarouselEpisodeIndexByIndex]", e);
            jsonStrResp = ServiceUtil.getResponseError(ERROR_EXIST);
        }
        return jsonStrResp;
    }


    public String moveAutomationIndexByIndex(long id, int aimIdx, long channelId) {
        String jsonStrResp = null;
        try {
            int result = getCarouselService().indexMoveAutomationByIndex(id, aimIdx);
            String code = null;
            if (result > 0) {
                code = Constants.CODE_SUC;
                jsonStrResp = Constants.getResponseList(Constants.CODE_SUC, null, Constants.getCode(code)).toJsonString();
            } else if (result == -2) {
                code = Constants.CODE_ERROR_AUTOMATION_RUNNING;
                jsonStrResp = Constants.getResponseList(Constants.CODE_ERROR, null, Constants.getCode(code)).toJsonString();
            } else {
                code = Constants.CODE_ERROR;
                jsonStrResp = ServiceUtil.getResponseError(PARAMETER_ERROR);
            }
            writeChannelLog(channelId, Constants.LogType.CAROUSEL_AUTOMATION_INDEX_MOVE.getIndex(), ServiceUtil.getOpUser(), Constants.getCode(code) + "|" + getStrParam());
        } catch (Exception e) {
            logger.error("[moveAutomationIndexByIndex]", e);
            jsonStrResp = ServiceUtil.getResponseError(ERROR_EXIST);
        }
        return jsonStrResp;
    }
}
